import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
import Fontisto from 'react-native-vector-icons/Fontisto';
import {StylesConstant} from '../Constant';

export default class Checkbox extends React.Component {
  // props
  // isCanCheckAll: true,
  // isRadio: false, // 单选
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked ? props.checked : [],
      isCheckAll: props.checked? props.checked : false,
      isCanCheckAll: true,
    };
  }

    shouldComponentUpdate(nextProps, nextState) {
        // 旧数据
        const current = this.props.checked;
        // 新数据
        const next = nextProps.checked;

        const flag = JSON.stringify(current) !== JSON.stringify(next)
        console.log('update: ',flag)
        if(flag){
          this.state.checked = next
        }
        return flag
    }



    render() {
    const iconColor = StylesConstant.themeIconColor;
    const dataArr = this.props.data || [];
    const isCheckAll = this.state.isCheckAll;
    let isCanCheckAll = this.state.isCanCheckAll;
    if (this.props.isCanCheckAll === false) {
      isCanCheckAll = false;
    }
    return (
      <View style={this.props.checkboxStyle}>
        {/* 全选 */}
        {dataArr.length > 0 && isCanCheckAll ? (
          <TouchableOpacity
            style={styles.item}
            activeOpacity={0.5}
            onPress={() => this.checkAll()}>
            <Fontisto
              style={styles.checkIcon}
              name={isCheckAll ? 'checkbox-active' : 'checkbox-passive'}
              size={14}
              color={iconColor}
            />
            <Text style={styles.label}>全选</Text>
          </TouchableOpacity>
        ) : null}
        {/* checkItem */}
        {dataArr.length > 0 ? (
          this.renderCheckItem(dataArr)
        ) : (
          <View
            style={{
              alignItems: 'center',
              justifyContent: 'center',
              height: 100,
            }}>
            <Text style={{color: '#ccc', fontSize: 16}}>暂无数据</Text>
          </View>
        )}
      </View>
    );
  }

  // 渲染checkItem
  renderCheckItem(dataArr) {
    const iconColor = StylesConstant.themeIconColor;
    const isRadio = this.props.isRadio;
    const checkedArr = this.state.checked;
    return dataArr.map((item, index) => {
      return (
        <TouchableOpacity
          style={styles.item}
          activeOpacity={0.5}
          key={index}
          onPress={() => this.setData(item, isRadio)}>
          <Fontisto
            style={styles.checkIcon}
            name={
              checkedArr.includes(item.value)
                ? isRadio
                  ? 'radio-btn-active'
                  : 'checkbox-active'
                : isRadio
                ? 'radio-btn-passive'
                : 'checkbox-passive'
            }
            size={14}
            color={iconColor}
          />
          <Text style={styles.label}>{item.label}</Text>
        </TouchableOpacity>
      );
    });
  }

  // 单击某一项
  setData(item, isRadio = false) {
    if (isRadio) {
      this.setState({
        checked: [item],
        isCheckAll: false,
      });
      this.props.onChange([item]);
    } else {
      // arr = ["{}", "{}", ...]
      const arr = this.state.checked.map((j) => JSON.stringify(j));
      // 先判断当前点击的 item 如果存在于已选数组里，则原位删除
      if (arr.includes(JSON.stringify(item))) {
        const delIndex = arr.findIndex((e) => e === JSON.stringify(item));
        arr.splice(delIndex, 1);
        const newArr = arr.map((j) => JSON.parse(j));
        // 更新 state
        this.setState({
          checked: newArr,
          isCheckAll: false,
        });
        this.props.onChange(newArr);
      } else {
        const oldValue = [...this.state.checked];
        const temp = [...oldValue, item];
        // 存到state里
        this.setState({
          checked: temp,
        });
        // 设置全选的状态
        if (temp.length === this.props.data.length) {
          this.setState({
            isCheckAll: true,
          });
        }
        this.props.onChange(temp);
      }
    }
  }

  // 全选
  checkAll() {
    // 如果当前是全选的状态
    if (this.state.isCheckAll) {
      this.setState({
        checked: [],
        isCheckAll: false,
      });
      this.props.onChange([]);
    } else {
      // 勾选所有子项
      this.setState({
        checked: this.props.data,
        isCheckAll: true,
      });
      this.props.onChange(this.props.data);
    }
  }
}

const styles = StyleSheet.create({
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 20,
  },
  checkIcon: {
    paddingRight: 10,
  },
  label: {
    fontSize: 16,
  },
});
